<template>
    <view class="question-header">
        <view class="left-group">
            <text class="question-index">第{{ currentQuestion + 1 }}题</text>
            <nut-avatar class="type-badge" shape="round" bg-color="#f90"
                style="width: 60px; height: 30px; font-size: 14px; color: #fff;">
                {{ questionTypeText }}
            </nut-avatar>
        </view>

        <view class="right-group">
            <IconFont class="icon" name="setting" size="32" @click="showSettings" />
            <IconFont class="icon" name="ask" size="32" @click="showFeedbackModal" />
        </view>
    </view>

    <!-- 设置弹窗 -->
    <nut-popup :visible="showSettingModal" @update:visible="$emit('update:showSettingModal', $event)" position="bottom"
        :style="{ height: '40%' }">
        <view class="popup-content">
            <nut-cell v-for="(cell, index) in settingCells" :key="index" :title="cell.title" :desc="cell.desc"
                @click="showPicker(index)" />
        </view>
        <view v-if="currentPickerIndex !== null" class="picker-container">
            <nut-picker :columns="settingCells[currentPickerIndex].arrays"
                :title="settingCells[currentPickerIndex].title" @confirm="handleConfirm" @cancel="hidePicker" />
        </view>
    </nut-popup>
    <!-- 问题反馈弹窗 -->
    <nut-popup :visible="showFeedback" @update:visible="$emit('update:showFeedback', $event)" position="bottom"
        :style="{ height: '40%' }">
        <view class="feedback-container">
            <!-- 标题栏：标题 + 关闭按钮 -->
            <view class="feedback-header">
                <text class="title">问题反馈</text>
                <IconFont name="close" size="16" @click="cancelFeedBack" class="close-icon" />
            </view>

            <!-- 输入框 -->
            <textarea class="feedback-input" v-model="feedbackContent" placeholder="请输入问题反馈，字数限制200字" :maxlength="200"
                auto-height></textarea>

            <!-- 字数统计 -->
            <view class="word-count">{{ feedbackContent.length }}/200</view>

            <!-- 按钮组 -->
            <view class="feedback-actions">
                <nut-button type="default" block @click="cancelFeedBack">取消</nut-button>
                <nut-button type="info" block @click="submitFeedback">确认</nut-button>
            </view>
        </view>
    </nut-popup>
</template>

<script setup>
import { ref, computed } from 'vue'
import { IconFont } from '@nutui/icons-vue'
import Taro from '@tarojs/taro'
import config from '../config.ts'
//因为命名规范的问题,vue模板中不区分驼峰命名的大小写.所以用短横线
const props = defineProps([
    'currentQuestion',
    'questionData',
    'showSettingModal',
    'showFeedback',
    'requestHandler',
    'autoNextEnabled'
])

const emit = defineEmits([
    'update:showSettingModal',
    'update:showFeedback',
    'set-font-size',
    'update:autoNextEnabled'
])

// 题型文本计算
const questionTypeText = computed(() => {
    switch (props.questionData.type) {
        case 1: return '单选题'
        case 2: return '多选题'
        case 3: return '判断题'
        default: return '未知题型'
    }
})

// 弹窗相关状态
const currentPickerIndex = ref(null)
const feedbackContent = ref('')
const selectedFontSizeLabel = ref('中')
//字体大小标识
const selectedFontSize = ref(['medium']) // 默认值：'large', 'medium', 'small'
//保存反馈的json格式
const feedbackData = ref({
  userId: null,
  questionId: null,
  content: '',
  handleContent: 0,
  createTime: ''
});
// 字体大小选项
const fontSizeOptions = [
    { text: '大', value: 'large', index: 0 },
    { text: '中', value: 'medium', index: 1 },
    { text: '小', value: 'small', index: 2 }
]
const columns = [
    {
        text: '是',
        value: true
    },
    {
        text: '否',
        value: false
    }
]
//设置弹窗的表格cell内容
const settingCells = [
    {
        title: '调整字体大小',
        desc: '中',
        arrays: fontSizeOptions

    },
    {
        title: '自动切换下一题',
        desc: '否',
        arrays: columns
    }
]
// 事件方法
function showSettings() { emit('update:showSettingModal', true) }
function showFeedbackModal() { emit('update:showFeedback', true) }
function showPicker(index) { currentPickerIndex.value = index }
// 字体大小变化处理
function onFontSizeChange(value, index) {
    const option = fontSizeOptions[index]
    selectedFontSize.value = [option.value] // 保持数组格式
    selectedFontSizeLabel.value = option.text

    // 通知父组件修改字体类名
    emit('set-font-size', option.value)
}
function handleConfirm(value) {
    console.log("我执行了", value)
    if (currentPickerIndex.value !== null) {
        const selectedItem = settingCells[currentPickerIndex.value];
        console.log("select", selectedItem)
        if (selectedItem) {
            // 更新 desc 字段
            console.log("selectedItem", value.selectedOptions)
            selectedItem.desc = value.selectedOptions[0].text;

            // 根据不同的 cell 做不同处理
            switch (currentPickerIndex.value) {
                case 0: // 字体大小
                    onFontSizeChange(value.selectedOptions[0].index, value.selectedOptions[0].index);
                    break;
                case 1: // 是否自动跳转
                    emit('update:autoNextEnabled',value.selectedOptions[0].value)
                    // onAutoNextChange(value.selectedOptions[0].value);
                    break;
                default:
                    console.log('未知设置项');
            }

            hidePicker(); // 关闭 picker
        }
    }
}
function hidePicker() { currentPickerIndex.value = null }
function cancelFeedBack() {
    emit('update:showFeedback', false)
    feedbackContent.value = ''
    console.log('取消反馈',props.showFeedback);
}
// 格式化时间为 "YYYY-MM-DD HH:mm"
const formatTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从 0 开始
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
}
async function submitFeedback() {
    if (feedbackContent.value.trim() === '') {
        Taro.showToast({ title: '反馈内容不能为空', icon: 'none' });
        return;
    }
    try {
        const wxRequest =  config.wxPromisify(wx.request);
        feedbackData.value = {
            //Taro.getStorageSync('userId')
            userId: 1,
            questionId: props.questionData.id,
            content: feedbackContent.value,
            handleContent: 0,
            createTime: formatTime(new Date())
        };
        const res = await wxRequest({
            url: `${config.apiUrl}/feedback/save`,
            method: 'POST',
            header: { 'Content-Type': 'application/json' },
            data: feedbackData.value
        })
        if (res.statusCode === '0') {
            Taro.showToast({ title: '提交成功' })
        }
    } catch (err) {
        console.error('请求失败:', err);
        Taro.showToast({ title: '网络错误', icon: 'none' });
    }

    // 清空内容并关闭弹窗
    feedbackContent.value = '';
    emit('update:showFeedback', false)
}

</script>

<style lang="scss">
</style>